package com.xiaoshuidi.cloud.module.report.service.finance;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaoshuidi.cloud.framework.common.exception.ServiceException;
import com.xiaoshuidi.cloud.framework.common.pojo.PageResult;
import com.xiaoshuidi.cloud.framework.oss.core.OosFileService;
import com.xiaoshuidi.cloud.framework.security.core.LoginUser;
import com.xiaoshuidi.cloud.framework.security.core.util.SecurityFrameworkUtils;
import com.xiaoshuidi.cloud.module.report.controller.finance.vo.*;
import com.xiaoshuidi.cloud.module.report.convert.finance.CollectInAdvanceConvert;
import com.xiaoshuidi.cloud.module.report.convert.finance.ReceivableConvert;
import com.xiaoshuidi.cloud.module.report.dal.DO.report.CollectInAdvanceDO;
import com.xiaoshuidi.cloud.module.report.dal.DO.report.ReceivableDO;
import com.xiaoshuidi.cloud.module.report.dal.mapper.report.CollectInAdvanceMapper;
import com.xiaoshuidi.cloud.module.report.dal.mapper.report.ReceivableMapper;
import com.xiaoshuidi.cloud.module.report.enums.ErrorCodeConstants;
import com.xiaoshuidi.cloud.module.report.framework.security.config.ConfigValues;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.math.BigDecimal;
import java.util.List;


@Service
@RequiredArgsConstructor
@Slf4j
public class ReceivableServiceImpl implements ReceivableService {

    private final ReceivableMapper receivableMapper;
    private final OosFileService oosFileService;
    private final ConfigValues configValues;

    @Override
    public ReceivableDO selectRentAdvanceByContractIdAndMonth(Long contractId , String statisticsMonth) {
        return receivableMapper.selectRentReceivableByContractIdAndMonth(contractId,statisticsMonth);
    }
    @Override
    public void batchInsert(List<ReceivableDO> list){
        receivableMapper.insertBatch(list);
    }
    @Override
    public void batchUpdate(List<ReceivableDO> list){
        receivableMapper.updateBatch(list,list.size());
    }

    @Override
    public ReceivablePageRespVO page(ReceivableReqVO reqVO) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if(loginUser==null){
            throw new ServiceException(ErrorCodeConstants.USER_NOT_LOGIN);
        }
        reqVO.setTenantId(loginUser.getTenantId());
        long num  = receivableMapper.countListForPage(reqVO);
        List<ReceivableDO> receivableDOList = receivableMapper.selectListForPage(reqVO);
        ReceivablePageRespVO respVO = new ReceivablePageRespVO();
        if(CollectionUtils.isEmpty(receivableDOList)){
            return respVO;
        }
        List<ReceivableRespVO> contractList = ReceivableConvert.INSTANCE.convertReceivableDOForPage(receivableDOList);
        ReceivableDO receivableDO = receivableMapper.selectTotalAmountInMonth(reqVO);
        respVO.setTotalCurReceivable(receivableDO.getCurReceivable());
        respVO.setTotalCurReceived(receivableDO.getCurReceived());
        respVO.setTotalCurNotReceived(receivableDO.getCurNotReceived());
        respVO.setTotalAccNotReceived(receivableDO.getAccNotReceived());
        respVO.setTotalCurAdvance(receivableDO.getCurAdvance());
        respVO.setTotal(num);
        respVO.setRespVOList(contractList);
        return respVO;
    }

    @Override
    public ExportRespVO export(ReceivableReqVO req) {
        //暂时不分页，当月合同数不会超过2000
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if(loginUser==null){
            throw new ServiceException(ErrorCodeConstants.USER_NOT_LOGIN);
        }
        req.setTenantId(loginUser.getTenantId());
        String fileName =  req.getStatisticsMonth() + "应收账款明细表.xlsx";
        String filePath = configValues.getNfsPath() + File.separator +fileName;
        ExcelWriter excelWriter = EasyExcel.write(filePath, ReceivableExportRespVO.class).build();
        WriteSheet sheet = EasyExcel.writerSheet("sheet1").build();
        List<ReceivableDO> receivableDOList = receivableMapper.selectListForExport(req);
        if(CollectionUtils.isEmpty(receivableDOList)){
            throw new ServiceException(ErrorCodeConstants.RECEIVABLE_NOT_EXISTS);
        }
        List<ReceivableExportRespVO> list = ReceivableConvert.INSTANCE.convertDOList2Export(receivableDOList);
        excelWriter.write(list, sheet);
        excelWriter.finish();
        //上传到oos返回URL
        String url = oosFileService.oosUploadFile(new File(filePath));
        ExportRespVO resp = new ExportRespVO();
        if(url.startsWith("http:")){
            url = url.replace("http:","https:");
        }
        resp.setUrl(url);
        resp.setFileName(fileName);
        return resp;
    }

    @Override
    public List<ReceivableDO> selectReceivableInCurrentMonth(String currentMonth,List<Long> contractIds) {
        LambdaQueryWrapper<ReceivableDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ReceivableDO::getStatisticsMonth, currentMonth);
        queryWrapper.in(ReceivableDO::getContractId, contractIds);
        return receivableMapper.selectList(queryWrapper);
    }
}
